package com.ccsoft.zknote.util;

import cn.hutool.core.io.resource.ClassPathResource;
import cn.hutool.core.io.resource.Resource;
import com.cc.commontools.entity.DirectoryNode;
import com.cc.commontools.entity.FieldInfo;
import com.cc.commontools.entity.NaiveTreeNode;
import com.cc.commontools.entity.TableInfo;
//import com.cc.commontools.utils.FileUtils;
import com.cc.commontools.utils.FreemarkerUtils;
import com.cc.commontools.utils.MySQLUtils;
import com.fasterxml.jackson.core.JsonProcessingException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.*;
import java.util.HashSet;
import java.util.List;
import java.util.Optional;
import java.util.Set;

import org.springframework.util.ResourceUtils;


@Slf4j
@Component
public class CodeGeneratorUtils {
    @Value("${system.template-path}")
    private String templatePath;
    @Value("${system.code-path}")
    private String codePath;
    @Autowired
    private ResourcesUtils resourcesUtils;

    //region 开放接口
    // 12月21日新增返回给前端生成的多个文件的名称构成的字符串集合
    public List<String> generateFile(FreemarkerUtils.GenerateConfig config) throws Exception {
        // 解决异步加载模式下表信息中没有相关字段信息的问题
        TableInfo tableInfo = config.getData().getTableInfo();
        List<FieldInfo> fieldInfoList = tableInfo.getFieldInfoList();
        if(fieldInfoList == null || fieldInfoList.size() == 0){
            List<FieldInfo> fieldInfoList1 = MySQLUtils.getFieldInfoList(config.getDbConfig(), tableInfo.getDbName(), tableInfo.getTableName());
            tableInfo.setFieldInfoList(fieldInfoList1);

            Set<String> imports = Optional.ofNullable(tableInfo.getImports()).orElse(new HashSet<>());
            for (FieldInfo fieldInfo : fieldInfoList1) {
                String importString = Optional.ofNullable(fieldInfo.getImportString()).orElse("");
                if(importString.length() > 0) imports.add(importString);
            }
            tableInfo.setImports(imports);
        }
//        FreemarkerUtils.generate(config);
        List<String> fileNameList = FreemarkerUtils.generate8Config(config, codePath);
        return fileNameList;
    }

    public NaiveTreeNode getTemplateTree() throws IOException {
        String projRootDirectory = ResourcesFileUtils.getProjRootDirectory();
        log.info("通过工具类FileUtils获取到的项目资源根目录是：" + projRootDirectory);
        String templateDirectory = projRootDirectory + "\\src\\main\\resources\\templates";
        log.info("拼接后的模板根目录是：" + templateDirectory);

        DirectoryNode rootNode = new DirectoryNode();
        NaiveTreeNode naiveTreeNode = new NaiveTreeNode();
        naiveTreeNode.setLabel("root");
        naiveTreeNode.setKey("root");

        ResourcesFileUtils.buildTree(templatePath,rootNode, naiveTreeNode);

        log.info("开始使用resourcesUtils读取资源");

        String s="";

        try {
            s = JsonUtils.toString(naiveTreeNode);
        } catch (JsonProcessingException e) {
            throw new RuntimeException("转换 naiveTreeNode 对象为字符串时出现异常！");
        }
        log.info("构建的naiveTree对象是：" + s);
        return naiveTreeNode;
    }
    //endregion

    //region 支持开放接口的私有方法
    //endregion

    public static void main(String[] args) throws FileNotFoundException {
        readResources();
    }
    public static void readResources() throws FileNotFoundException {
        String resourcePath = "classpath:templates";
        String rootFolder = resourcePath.substring(resourcePath.indexOf(":")+1);
        System.out.println("资源目录下的一级目录：" + rootFolder);
        readResourcePath(resourcePath, rootFolder);
    }
    public static void readResourcePath(String path,String rootFolder) throws FileNotFoundException {
        File rootPath = ResourceUtils.getFile(path);
        if(rootPath.exists()){
            File[] files = rootPath.listFiles();
            for (File file : files) {
                if (file.isDirectory()) {
                    readResourcePath(file.getAbsolutePath(), rootFolder);
                } else {
                    // 获取绝对路径：D:\source\java\zknotebe\target\classes\templates\java\cc\baseWithExample\${tableInfo.modelClassName}.java
                    String absolutePath = file.getAbsolutePath();
                    // 截取路径，从 resources 下指定名称的路径开始：templates\java\cc\baseWithExample\${tableInfo.modelClassName}.java
                    String ftlFileName = absolutePath.substring(absolutePath.indexOf(rootFolder));
                    //System.out.println("_____________________" + ftlFileName + "___________begin__________");
                    System.out.println("文件名：" + ftlFileName);

                    BufferedReader reader = null;
                    StringBuffer sbf = new StringBuffer();
                    try {
                        reader = new BufferedReader(new FileReader(file));
                        String tempStr;
                        while ((tempStr = reader.readLine()) != null) {
                            sbf.append(tempStr).append("\n");
                        }
                        reader.close();

                        //System.out.println(sbf.substring(0, sbf.length() - 1));
                        //System.out.println("文件名：" + file.getName());
                    } catch (IOException e) {
                        e.printStackTrace();
                    } finally {
                        if (reader != null) {
                            try {
                                reader.close();
                            } catch (IOException e1) {
                                e1.printStackTrace();
                            }
                        }
                    }
                }
            }
        }else{
            System.out.println("path:" + path + "not exists");
        }
    }
}
